# 密码配置文件
# 用于各量表数据导出的密码管理
import os
import time

# 密码文件路径
PASSWORD_FILE = "passwords_backup.txt"

# 全局变量：缓存密码和文件修改时间
_EXPORT_PASSWORDS = None
_PASSWORD_FILE_MTIME = None


def load_passwords_from_file() -> dict:
    """
    从密码文件中加载密码

    Returns:
        dict: 密码字典，键为量表类型，值为密码
    """
    passwords = {}

    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    password_file_path = os.path.join(current_dir, PASSWORD_FILE)

    # 如果密码文件存在，读取密码
    if os.path.exists(password_file_path):
        try:
            with open(password_file_path, "r", encoding="utf-8") as f:
                for line in f:
                    # 忽略空行和注释行
                    line = line.strip()
                    if not line or line.startswith("#"):
                        continue

                    # 解析格式: 量表类型:密码
                    if ":" in line:
                        parts = line.split(":", 1)
                        if len(parts) == 2:
                            key = parts[0].strip()
                            value = parts[1].strip()
                            passwords[key] = value
        except Exception as e:
            print(f"读取密码文件失败: {e}")
            print(f"使用默认密码")

    # 如果没有读取到密码，使用硬编码的默认密码作为备用
    if not passwords:
        print("警告: 未找到密码文件或密码文件为空，使用默认密码")
        passwords = {
            "default": "admin123",
            "survey": "admin123",
            "rockwood": "admin123",
            "gpm": "admin123",
            "nrs": "admin123",
            "psqi": "admin123",
            "hamd": "admin123",
            "oral": "admin123",
            "ohip14": "admin123",
            "personalinfo": "admin123",
            "cognitive": "admin123",
            "personality": "admin123",
            "outdooractivity": "admin123",
            "leisureactivity": "admin123",
            "indooractivity": "admin123",
            "batch": "admin123",
        }

    return passwords


def _get_password_file_mtime():
    """获取密码文件的修改时间"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    password_file_path = os.path.join(current_dir, PASSWORD_FILE)
    if os.path.exists(password_file_path):
        return os.path.getmtime(password_file_path)
    return None


def _reload_passwords_if_needed():
    """如果密码文件被修改，重新加载密码"""
    global _EXPORT_PASSWORDS, _PASSWORD_FILE_MTIME
    
    current_mtime = _get_password_file_mtime()
    
    # 如果文件被修改或首次加载，重新加载密码
    if _EXPORT_PASSWORDS is None or _PASSWORD_FILE_MTIME != current_mtime:
        _EXPORT_PASSWORDS = load_passwords_from_file()
        _PASSWORD_FILE_MTIME = current_mtime
        if current_mtime:
            print(f"密码文件已重新加载 (修改时间: {time.ctime(current_mtime)})")


def get_password(survey_type: str) -> str:
    """
    获取指定量表的导出密码
    每次调用时会检查密码文件是否被修改，如果修改了会自动重新加载

    Args:
        survey_type: 量表类型，如 'survey', 'rockwood', 'gpm' 等

    Returns:
        对应的密码字符串
    """
    _reload_passwords_if_needed()
    return _EXPORT_PASSWORDS.get(
        survey_type, _EXPORT_PASSWORDS.get("default", "admin123")
    )


def set_password(survey_type: str, new_password: str):
    """
    设置指定量表的导出密码（动态修改，不保存到文件）

    Args:
        survey_type: 量表类型
        new_password: 新密码
    """
    _reload_passwords_if_needed()
    _EXPORT_PASSWORDS[survey_type] = new_password
